package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// Room 包厢模型
type Room struct {
	BaseModel
	Name        string  `orm:"size(100)" json:"name"`
	StoreId     int64   `orm:"index" json:"store_id"`                    // 所属门店ID
	Capacity    int     `orm:"default(0)" json:"capacity"`               // 容纳人数
	Area        float64 `orm:"digits(10);decimals(2)" json:"area"`       // 面积（平方米）
	HourPrice   float64 `orm:"digits(10);decimals(2)" json:"hour_price"` // 小时价格
	DayPrice    float64 `orm:"digits(10);decimals(2)" json:"day_price"`  // 全天价格
	Description string  `orm:"size(500)" json:"description"`
	Facilities  string  `orm:"size(500)" json:"facilities"`  // 设施，JSON格式存储
	Images      string  `orm:"size(1000)" json:"images"`     // 包厢图片，JSON格式存储
	Status      int8    `orm:"default(1)" json:"status"`     // 1:可用, 0:维护中
	SortOrder   int     `orm:"default(0)" json:"sort_order"` // 排序
}

// TableName 设置表名
func (r *Room) TableName() string {
	return "ss_room"
}

// GetRoomById 根据ID获取包厢信息
func GetRoomById(id int64) (*Room, error) {
	room := &Room{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(room)
	return room, err
}

// GetRoomList 获取包厢列表
func GetRoomList(page, pageSize int, filters map[string]interface{}) ([]*Room, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Room))

	// 应用过滤条件
	if storeId, ok := filters["store_id"].(int64); ok {
		qs = qs.Filter("store_id", storeId)
	}

	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	if minCapacity, ok := filters["min_capacity"].(int); ok {
		qs = qs.Filter("capacity__gte", minCapacity)
	}

	if maxCapacity, ok := filters["max_capacity"].(int); ok {
		qs = qs.Filter("capacity__lte", maxCapacity)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var rooms []*Room
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&rooms)

	return rooms, total, err
}

// CreateRoom 创建包厢
func CreateRoom(room *Room) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(room)
	return id, err
}

// UpdateRoom 更新包厢信息
func UpdateRoom(room *Room, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(room, fields...)
	return err
}

// DeleteRoom 删除包厢（软删除）
func DeleteRoom(id int64) error {
	o := orm.NewOrm()
	room := &Room{BaseModel: BaseModel{Id: id}}
	if err := o.Read(room); err != nil {
		return err
	}

	room.IsDeleted = 1
	_, err := o.Update(room, "IsDeleted")
	return err
}

// GetRoomsByStoreId 获取指定门店的包厢列表
func GetRoomsByStoreId(storeId int64) ([]*Room, error) {
	o := orm.NewOrm()
	var rooms []*Room
	_, err := o.QueryTable(new(Room)).Filter("store_id", storeId).Filter("is_deleted", 0).OrderBy("sort_order", "-id").All(&rooms)
	return rooms, err
}
